/**
 * SQL构建工具类，负责生成各种SQL语句
 */
export class SqlBuilderUtils {
  /**
   * 创建SQL语句的占位符
   * @param count 占位符数量
   * @returns 逗号分隔的问号占位符
   */
  static createPlaceholders(count: number): string {
    return Array(count).fill('?').join(', ');
  }

  /**
   * 构建INSERT语句
   * @param tableName 表名
   * @param keys 字段名数组
   * @returns INSERT SQL语句
   */
  static buildInsertSql(tableName: string, keys: string[]): string {
    const placeholders = this.createPlaceholders(keys.length);
    return `INSERT INTO ${tableName} (${keys.join(', ')}) VALUES (${placeholders})`;
  }

  /**
   * 构建UPDATE语句
   * @param tableName 表名
   * @param keys 要更新的字段名数组
   * @param wherePairs WHERE条件的键值对
   * @returns UPDATE SQL语句
   */
  static buildUpdateSql(
    tableName: string,
    keys: string[],
    wherePairs: [string, any][]
  ): string {
    return `
      UPDATE ${tableName} 
      SET ${keys.map(key => `${key} = ?`).join(', ')} 
      WHERE ${wherePairs.map(([key]) => `${key} = ?`).join(' AND ')}
    `;
  }

  /**
   * 构建DELETE语句
   * @param tableName 表名
   * @param wherePairs WHERE条件的键值对
   * @returns DELETE SQL语句
   */
  static buildDeleteSql(
    tableName: string,
    wherePairs: [string, any][]
  ): string {
    return `
      DELETE FROM ${tableName} 
      WHERE ${wherePairs.map(([key]) => `${key} = ?`).join(' AND ')}
    `;
  }

  /**
   * 构建SELECT语句
   * @param tableName 表名
   * @param fields 要查询的字段，默认为*
   * @param whereClause WHERE子句，可选
   * @param orderByClause ORDER BY子句，可选
   * @param limitClause LIMIT子句，可选
   * @returns SELECT SQL语句
   */
  static buildSelectSql(
    tableName: string,
    fields: string[] = ['*'],
    whereClause?: string,
    orderByClause?: string,
    limitClause?: string
  ): string {
    let sql = `SELECT ${fields.join(', ')} FROM ${tableName}`;

    if (whereClause) {
      sql += ` WHERE ${whereClause}`;
    }

    if (orderByClause) {
      sql += ` ORDER BY ${orderByClause}`;
    }

    if (limitClause) {
      sql += ` ${limitClause}`;
    }

    return sql;
  }

  /**
   * 构建COUNT语句
   * @param tableName 表名
   * @param whereClause WHERE子句，可选
   * @returns COUNT SQL语句
   */
  static buildCountSql(
    tableName: string,
    whereClause?: string
  ): string {
    let sql = `SELECT COUNT(*) as count FROM ${tableName}`;

    if (whereClause) {
      sql += ` WHERE ${whereClause}`;
    }

    return sql;
  }
} 